package com.client;

import com.alibaba.fastjson.JSON;
import com.client.handler.ClientHandler;
import com.client.handler.ClientInitializer;
import com.entity.AppInfo;
import com.entity.MsgData;
import com.entity.MsgType;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.ResourceLeakDetector;

import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class TestNettyClient {

    public static void main(String args[]) throws Exception {
//        ResourceLeakDetector.setLevel();
        String serverIp = "127.0.0.1";
        int tcpPort  = 9876;
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ClientInitializer(new ClientHandler()));
        ChannelFuture future = bootstrap.connect(serverIp, tcpPort).sync();

        Channel channel = future.channel();
        if (!future.isSuccess()) {
            future.cause().printStackTrace();
        }

        for (int i=0;i<10;i++){
            String msg = "client msg"+i;
            MsgData data = new MsgData();
            data.setType(MsgType.PING);
            AppInfo appInfo = new AppInfo();
            appInfo.setIp("192.168.56.1");
            appInfo.setAppId("demo-aliyun");
            appInfo.setChannel("aliyun");
            data.setAppInfo(appInfo);
            data.setMsg(msg);
            DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/1/netty",
                    Unpooled.wrappedBuffer(JSON.toJSONString(data).getBytes()));

//            ByteBuf byteBuf = Unpooled.wrappedBuffer(msg.getBytes());
            channel.writeAndFlush(request);
            Thread.sleep(10000);
        }
    }
}
